package lv.solcraft.replication.client.rest;

import lv.solcraft.replication.client.boot.Booter;
import lv.solcraft.replication.client.boot.StartupOptions;
import lv.solcraft.replication.client.rest.restlets.RestartClientRestlet;
import lv.solcraft.replication.client.rest.restlets.StopClientRestlet;

import org.apache.log4j.Logger;
import org.restlet.Application;
import org.restlet.Context;
import org.restlet.Restlet;
import org.restlet.Router;

public class ReplicationClientApplication extends Application {

    private static final Logger log = Logger.getLogger(ReplicationClientApplication.class);
    private Booter booter;

    public ReplicationClientApplication(Context context, StartupOptions startupOptions) {
        super(context);
        booter = new Booter(startupOptions);
        try {
            booter.start();
        } catch (Exception e) {
            log.error("Replication client startup failed, " + e.getMessage(), e);
        }
    }

    @Override
    public Restlet createRoot() {
        Router router = new Router();
        attach(router, "/client/stop", new StopClientRestlet(getContext()));
        attach(router, "/client/restart", new RestartClientRestlet(getContext()));
        return router;
    }

    protected void attach(Router router, String pattern, Restlet restlet) {
        ErrorFilter errorFilter = new ErrorFilter();
        errorFilter.setNext(restlet);
        router.attach(pattern, errorFilter);
    }

    @Override
    public void stop() throws Exception {
        log.info("Stopping replication client");
        if (booter != null)
            booter.stop();
        super.stop();
        log.info("Stopped replication client");
    }

    @Override
    public void start() throws Exception {
        log.info("Starting replication client");
        super.start();
        log.info("Started replication client");
    }
}
